package paymentSystem;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public final class Http {

	private Http() {

	}

	public static synchronized String post(String destination,
			NameValuePair... pairs) throws HttpException, IOException {
		
		String result;
		HttpClient client;
		BufferedReader br;
		PostMethod method;
		System.out.println("dentro post");
		result= "";
		client = new HttpClient();
		System.out.println("client");
		br = null;

		method = new PostMethod(destination);
		System.out.println("postMethod");
		for(NameValuePair pair:pairs){
			method.addParameter(pair.getName(), pair.getValue());
		}
		System.out.println("prima del try");
		try {
			System.out.println("prima di execute");
			int returnCode = client.executeMethod(method);
			System.out.println("dopo execute");
			System.out.println("returnCode= "+returnCode);
			switch(returnCode){
			case HttpStatus.SC_NOT_IMPLEMENTED:{	
				// still consume the response body
				method.getResponseBodyAsString();
				throw new UnsupportedOperationException();
			}
			case HttpStatus.SC_OK:{
				System.out.println("leggo");
				br = new BufferedReader(new InputStreamReader(method
						.getResponseBodyAsStream()));
				String readLine;
				while (((readLine = br.readLine()) != null)) {	
					result += readLine;
				}
				System.out.println("fine lettura" + result);
				break;
			}
			default:{	
				throw new IOException();
			}
			}
		} finally {
			method.releaseConnection();
			if (br != null) {
				try {
					br.close();
				} catch (Exception fe) {

				}
			}
			System.out.println("fine dentro post");
		}

		return result;
	}

}
